package service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pojo.Roles;
import pojo.UserProfile;
import dao.UserDAO;

@Service  
@Transactional(readOnly=true) 
public class CustomerUserDetailsService implements UserDetailsService {

	 @Autowired  
	 private UserDAO UserDAO;    
	 
	public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
		UserProfile domainUser = UserDAO.getUserProfile(arg0);
		
		boolean enabled = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;  
        
        Roles role = (Roles)domainUser.getRoleses().iterator().next();
        User user = new User( domainUser.getEmail(), domainUser.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(role)); 
        return user;
	}
	
	public Collection<? extends GrantedAuthority> getAuthorities(Roles role) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
		return authList;
	}
	
	public List<String> getRoles(Roles role) {

		List<String> roles = new ArrayList<String>();

		if (role.getId().intValue() == 1) {
			roles.add("ROLE_USER");
		}
		else if (role.getId().intValue() == 2) {
			roles.add("ROLE_USER");
			roles.add("ROLE_MODERATOR");
		}
		else if (role.getId().intValue() == 3) {
			roles.add("ROLE_USER");
			roles.add("ROLE_MODERATOR");
			roles.add("ROLE_ADMIN");
		}
		return roles;
	}
	
	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
	
}
